package org.csu.onlineedubackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.onlineedubackend.dto.LessonProgressDetailDTO;
import org.csu.onlineedubackend.dto.StudentCourseDTO;
import org.csu.onlineedubackend.dto.StudentProgressDTO;
import org.csu.onlineedubackend.entity.*;
import org.csu.onlineedubackend.mapper.*;

import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.entity.CourseSubscribe;
import org.csu.onlineedubackend.entity.StudentCourse;
import org.csu.onlineedubackend.mapper.CourseMapper;
import org.csu.onlineedubackend.mapper.CourseSubscribeMapper;
import org.csu.onlineedubackend.mapper.StudentCourseMapper;
import org.csu.onlineedubackend.service.StudentCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Date;

@Service
@Slf4j
public class StudentCourseServiceImpl implements StudentCourseService {

    @Autowired
    private StudentCourseMapper studentCourseMapper;
    
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LessonProgressMapper lessonProgressMapper;
    @Autowired
    private LessonMapper lessonMapper;
    @Autowired ChapterMapper chapterMapper;
    @Autowired QuestionMapper questionMapper;
    @Autowired StudentAnswerMapper studentAnswerMapper;

    @Autowired
    private VideoStudentCourseProgressMapper videoStudentCourseProgressMapper;

    
    @Autowired
    private CourseSubscribeMapper courseSubscribeMapper;
    
    @PostConstruct
    public void init() {
        log.info("StudentCourseServiceImpl初始化 - courseSubscribeMapper是否为null: {}", courseSubscribeMapper == null);
    }

    @Override
    @Transactional
    public boolean subscribe(Integer studentId, Integer courseId, String level, boolean isFree) {

        log.info("订阅课程 - 学生ID: {}, 课程ID: {}, 级别: {}, 是否免费: {}", studentId, courseId, level, isFree);
        
        try {
            // 首先检查课程是否存在
            Course existingCourse = courseMapper.selectById(courseId);
            if (existingCourse == null) {
                log.error("订阅课程失败 - 课程不存在, 课程ID: {}", courseId);
                System.out.println("订阅课程失败 - 课程不存在, 课程ID: " + courseId);
                throw new RuntimeException("课程不存在，无法订阅");
            }
            
            // 检查是否已订阅
            QueryWrapper<StudentCourse> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id", studentId).eq("course_id", courseId);
            Long count = studentCourseMapper.selectCount(wrapper);
            
            if (count != null && count > 0) {
                log.info("学生已订阅该课程 - 学生ID: {}, 课程ID: {}", studentId, courseId);
                return true; // 已订阅
            }
            
            // 创建新订阅
            StudentCourse sc = new StudentCourse();
            sc.setStudentId(studentId);
            sc.setCourseId(courseId);
            sc.setLevel(level);
            sc.setStatus(isFree ? "paid" : "unpaid");
            sc.setPaidAt(isFree ? LocalDateTime.now() : null);
            sc.setProgress(0f);
            sc.setLastLearnTime(isFree ? LocalDateTime.now() : null);
            
            try {
                // 插入订阅记录到student_course表
                int result = studentCourseMapper.insert(sc);
                if (result <= 0) {
                    log.error("插入student_course表失败 - 学生ID: {}, 课程ID: {}", studentId, courseId);
                    System.out.println("插入student_course表失败 - 学生ID: " + studentId + ", 课程ID: " + courseId);
                    throw new RuntimeException("插入student_course表失败");
                }
                log.info("插入student_course表成功 - 学生ID: {}, 课程ID: {}", studentId, courseId);
            } catch (Exception e) {
                log.error("插入student_course表异常 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage());
                System.out.println("插入student_course表异常详细信息：");
                e.printStackTrace();
                throw e; // 重新抛出异常以触发事务回滚
            }
            
            try {
                // 同时添加订阅记录到course_subscribe表
                CourseSubscribe subscribe = new CourseSubscribe();
                subscribe.setCourseId(courseId);
                subscribe.setStudentId(studentId);
                subscribe.setCreatedAt(LocalDateTime.now());
                int subscribeResult = courseSubscribeMapper.insert(subscribe);
                if (subscribeResult <= 0) {
                    log.error("插入course_subscribe表失败 - 学生ID: {}, 课程ID: {}", studentId, courseId);
                    System.out.println("插入course_subscribe表失败 - 学生ID: " + studentId + ", 课程ID: " + courseId);
                    throw new RuntimeException("插入course_subscribe表失败");
                }
                log.info("插入course_subscribe表成功 - 学生ID: {}, 课程ID: {}", studentId, courseId);
            } catch (Exception e) {
                log.error("插入course_subscribe表异常 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage());
                System.out.println("插入course_subscribe表异常详细信息：");
                e.printStackTrace();
                throw e; // 重新抛出异常以触发事务回滚
            }
            
            try {
                // 更新课程订阅数
                Course course = courseMapper.selectById(courseId);
                if (course != null) {
                    course.setSubscriberCount(course.getSubscriberCount() + 1);
                    int updateResult = courseMapper.updateById(course);
                    if (updateResult <= 0) {
                        log.error("更新课程订阅数失败 - 课程ID: {}", courseId);
                        System.out.println("更新课程订阅数失败 - 课程ID: " + courseId);
                        throw new RuntimeException("更新课程订阅数失败");
                    }
                    log.info("更新课程订阅数成功 - 课程ID: {}, 新订阅数: {}", courseId, course.getSubscriberCount());
                }
            } catch (Exception e) {
                log.error("更新课程订阅数异常 - 课程ID: {}, 错误: {}", courseId, e.getMessage());
                System.out.println("更新课程订阅数异常详细信息：");
                e.printStackTrace();
                throw e; // 重新抛出异常以触发事务回滚
            }
            
            return true;
        } catch (Exception e) {
            log.error("订阅课程失败 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage(), e);
            System.out.println("订阅课程失败异常详细信息：");
            e.printStackTrace();
            throw new RuntimeException("订阅课程失败: " + e.getMessage()); // 抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional
    public boolean unsubscribe(Integer studentId, Integer courseId) {
        log.info("取消订阅课程 - 学生ID: {}, 课程ID: {}", studentId, courseId);
        
        try {
            // 首先检查课程是否存在
            Course existingCourse = courseMapper.selectById(courseId);
            if (existingCourse == null) {
                log.warn("取消订阅课程 - 课程不存在, 课程ID: {}", courseId);
                System.out.println("取消订阅课程 - 课程不存在, 课程ID: " + courseId);
                // 如果课程不存在，我们仍然尝试删除可能存在的订阅记录
            }
            
            try {
                // 1. 删除student_course表中的记录
                QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
                scWrapper.eq("student_id", studentId).eq("course_id", courseId);
                int scResult = studentCourseMapper.delete(scWrapper);
                log.info("删除student_course表记录结果 - 学生ID: {}, 课程ID: {}, 结果: {}", studentId, courseId, scResult > 0);
            } catch (Exception e) {
                log.error("删除student_course表记录异常 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage());
                System.out.println("删除student_course表记录异常详细信息：");
                e.printStackTrace();
                throw e; // 重新抛出异常以触发事务回滚
            }
            
            try {
                // 2. 删除course_subscribe表中的记录
                QueryWrapper<CourseSubscribe> csWrapper = new QueryWrapper<>();
                csWrapper.eq("student_id", studentId).eq("course_id", courseId);
                int csResult = courseSubscribeMapper.delete(csWrapper);
                log.info("删除course_subscribe表记录结果 - 学生ID: {}, 课程ID: {}, 结果: {}", studentId, courseId, csResult > 0);
            } catch (Exception e) {
                log.error("删除course_subscribe表记录异常 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage());
                System.out.println("删除course_subscribe表记录异常详细信息：");
                e.printStackTrace();
                throw e; // 重新抛出异常以触发事务回滚
            }
            
            try {
                // 3. 更新课程订阅数
                Course course = courseMapper.selectById(courseId);
                if (course != null && course.getSubscriberCount() > 0) {
                    course.setSubscriberCount(course.getSubscriberCount() - 1);
                    int updateResult = courseMapper.updateById(course);
                    if (updateResult > 0) {
                        log.info("更新课程订阅数成功 - 课程ID: {}, 新订阅数: {}", courseId, course.getSubscriberCount());
                    } else {
                        log.warn("更新课程订阅数失败 - 课程ID: {}", courseId);
                    }
                } else {
                    log.warn("更新课程订阅数 - 课程不存在或订阅数已为0, 课程ID: {}", courseId);
                }
            } catch (Exception e) {
                log.error("更新课程订阅数异常 - 课程ID: {}, 错误: {}", courseId, e.getMessage());
                System.out.println("更新课程订阅数异常详细信息：");
                e.printStackTrace();
                // 这里我们不抛出异常，因为即使更新订阅数失败，取消订阅的主要操作（删除记录）可能已经成功
            }
            
            // 只要有一个表的记录被删除，就认为取消订阅成功
            return true;
        } catch (Exception e) {
            log.error("取消订阅课程失败 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage(), e);
            System.out.println("取消订阅课程失败异常详细信息：");
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    public boolean isSubscribed(Integer studentId, Integer courseId) {
        log.info("查询课程订阅状态 - 学生ID: {}, 课程ID: {}", studentId, courseId);
        
        try {
            // 首先检查参数是否有效
            if (studentId == null || courseId == null) {
                log.warn("查询订阅状态失败 - 参数无效, 学生ID: {}, 课程ID: {}", studentId, courseId);
                return false;
            }
            
            // 首先检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("查询订阅状态失败 - 课程不存在, 课程ID: {}", courseId);
                return false; // 课程不存在，视为未订阅
            }
            
            // 检查student_course表
            try {
                QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
                scWrapper.eq("student_id", studentId).eq("course_id", courseId).eq("status", "paid");
                Long scCount = studentCourseMapper.selectCount(scWrapper);
                
                // 如果student_course表中找到记录，则已订阅
                if (scCount != null && scCount > 0) {
                    log.info("在student_course表中找到订阅记录 - 学生ID: {}, 课程ID: {}", studentId, courseId);
                    return true;
                }
            } catch (Exception e) {
                log.error("查询student_course表失败 - 学生ID: {}, 课程ID: {}, 错误: {}", 
                        studentId, courseId, e.getMessage());
                // 继续检查course_subscribe表
            }
            
            // 如果student_course表中没有找到或查询失败，则检查course_subscribe表
            try {
                if (courseSubscribeMapper == null) {
                    log.error("courseSubscribeMapper为null，无法查询订阅状态");
                    return false;
                }
                
                QueryWrapper<CourseSubscribe> csWrapper = new QueryWrapper<>();
                csWrapper.eq("student_id", studentId).eq("course_id", courseId);
                Long csCount = courseSubscribeMapper.selectCount(csWrapper);
                
                boolean isSubscribed = csCount != null && csCount > 0;
                log.info("在course_subscribe表中查询订阅状态 - 学生ID: {}, 课程ID: {}, 是否订阅: {}", 
                        studentId, courseId, isSubscribed);
                return isSubscribed;
            } catch (Exception e) {
                log.error("查询course_subscribe表失败 - 学生ID: {}, 课程ID: {}, 错误: {}", 
                        studentId, courseId, e.getMessage(), e);
                // 如果course_subscribe表查询失败，则回退到只检查student_course表的结果
                return false;
            }
        } catch (Exception e) {
            log.error("查询订阅状态失败 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage(), e);
            return false;
        }
    }

//    @Override
//    public List<StudentProgressDTO> getStudentsWithProgress(Integer courseId, Integer teacherId) {
//        List<StudentCourse> studentCourses = studentCourseMapper.selectList(
//                new QueryWrapper<StudentCourse>().eq("course_id", courseId)
//        );
//
//        // 查询课程所有课时（带章节标题）
//        List<Lesson> lessons = lessonMapper.getLessonsByCourseId(courseId); // 你需自定义该方法
//        // 查询所有章节，形成 id -> title 映射
//        Map<Integer, String> chapterMap = chapterMapper.selectList(
//                new QueryWrapper<Chapter>().eq("course_id", courseId)
//        ).stream().collect(Collectors.toMap(Chapter::getId, Chapter::getTitle));
//
//        List<StudentProgressDTO> result = new ArrayList<>();
//
//        for (StudentCourse sc : studentCourses) {
//            User student = userMapper.selectById(sc.getStudentId());
//            if (student == null) continue;
//
//            StudentProgressDTO dto = new StudentProgressDTO();
//            dto.setId(student.getId());
//            dto.setName(student.getUsername());
//            dto.setPhone(student.getPhone());
//            dto.setAvatar(student.getAvatar());
//
//            List<LessonProgress> progresses = lessonProgressMapper.selectByStudentId(sc.getStudentId());
//            Map<Integer, Float> progressMap = new HashMap<>();
//            int completed = 0;
//
//            for (LessonProgress lp : progresses) {
//                float p = lp.getProgress();
//                progressMap.put(lp.getLessonId(), p);
//                if (p >= 100.0) {
//                    completed++;
//                }
//            }
//
//            dto.setProgress(progressMap);
//            dto.setCompletedLessons(completed);
//            dto.setTotalProgress((int) progressMap.values().stream().mapToDouble(Float::doubleValue).average().orElse(0.0));
//
//            //  新增：构建每个课时的详细进度信息
//            List<LessonProgressDetailDTO> details = new ArrayList<>();
//            for (Lesson lesson : lessons) {
//                LessonProgressDetailDTO d = new LessonProgressDetailDTO();
//                d.setLessonId(lesson.getId());
//                d.setLessonTitle(lesson.getTitle());
//                d.setChapterTitle(chapterMap.get(lesson.getChapterId()));
//                d.setProgress(progressMap.getOrDefault(lesson.getId(), 0.0f));
//                details.add(d);
//            }
//            dto.setLessonProgressDetails(details); // 添加到 DTO
//
//            result.add(dto);
//        }
//
//        return result;
//    }
@Override
public List<StudentProgressDTO> getStudentsWithProgress(Integer courseId, Integer teacherId) {
    // 1. 查询所有订阅该课程的学生
    List<CourseSubscribe> subscribes = courseSubscribeMapper.selectList(
            new QueryWrapper<CourseSubscribe>().eq("course_id", courseId)
    );

    // 2. 查询课程所有课时（带章节标题）
    List<Lesson> lessons = lessonMapper.getLessonsByCourseId(courseId);
    Map<Integer, String> chapterMap = chapterMapper.selectList(
            new QueryWrapper<Chapter>().eq("course_id", courseId)
    ).stream().collect(Collectors.toMap(Chapter::getId, Chapter::getTitle));

    List<StudentProgressDTO> result = new ArrayList<>();
    List<Integer> lessonIds = lessons.stream().map(Lesson::getId).collect(Collectors.toList());

    for (CourseSubscribe sub : subscribes) {
        User student = userMapper.selectById(sub.getStudentId());
        if (student == null) continue;

        StudentProgressDTO dto = new StudentProgressDTO();
        dto.setId(student.getId());
        dto.setName(student.getName());
        dto.setPhone(student.getPhone());
        dto.setAvatar(student.getAvatar());
        dto.setSubscribeTime(sub.getCreatedAt()); // 关键：赋值订阅时间

//        // 3. 查询进度
//        List<LessonProgress> progresses = lessonProgressMapper.selectByStudentId(sub.getStudentId());
//        Map<Integer, Float> progressMap = new HashMap<>();
//        int completed = 0;
//
//        for (LessonProgress lp : progresses) {
//            float p = lp.getProgress();
//            progressMap.put(lp.getLessonId(), p);
//            if (p >= 100.0) {
//                completed++;
//            }
//        }
//
//        dto.setProgress(progressMap);
//        dto.setCompletedLessons(completed);
//        dto.setTotalProgress((int) progressMap.values().stream().mapToDouble(Float::doubleValue).average().orElse(0.0));

        // 只查本课程的课时进度
        List<LessonProgress> progresses = lessonProgressMapper.selectByStudentIdAndLessonIds(sub.getStudentId(), lessonIds);

        Map<Integer, Float> progressMap = new HashMap<>();
        int completed = 0;
        for (Lesson lesson : lessons) {
            float p = 0.0f;
            for (LessonProgress lp : progresses) {
                if (lp.getLessonId().equals(lesson.getId())) {
                    p = lp.getProgress();
                    break;
                }
            }
            progressMap.put(lesson.getId(), p);
            if (p >= 100.0) {
                completed++;
            }
        }
        dto.setProgress(progressMap);
        dto.setCompletedLessons(completed);

        // 总进度=本课程所有课时的平均值
        double totalProgress = lessons.stream()
                .mapToDouble(lesson -> progressMap.getOrDefault(lesson.getId(), 0.0f))
                .average()
                .orElse(0.0);
        dto.setTotalProgress((int) totalProgress);

        // 4. 课时详细进度
        List<LessonProgressDetailDTO> details = new ArrayList<>();
        for (Lesson lesson : lessons) {
            LessonProgressDetailDTO d = new LessonProgressDetailDTO();
            d.setLessonId(lesson.getId());
            d.setLessonTitle(lesson.getTitle());
            d.setChapterTitle(chapterMap.get(lesson.getChapterId()));
            d.setProgress(progressMap.getOrDefault(lesson.getId(), 0.0f));
            details.add(d);
        }
        dto.setLessonProgressDetails(details);

        result.add(dto);
    }

    return result;
}

    @Override
    public List<StudentCourseDTO> getStudentCourses(Integer studentId) {
        log.info("获取学生课程列表 - 学生ID: {}", studentId);
        
        try {
            // 获取学生的所有已支付课程
            QueryWrapper<StudentCourse> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id", studentId).eq("status", "paid");

            //wrapper.eq("student_id", studentId); // 不再限制 status，返回所有订阅记录
            List<StudentCourse> studentCourses = studentCourseMapper.selectList(wrapper);
            log.info("查询到学生课程数量 - 学生ID: {}, 课程数: {}", studentId, studentCourses.size());
            
            // 构建返回结果
            List<StudentCourseDTO> result = new ArrayList<>();
            
            for (StudentCourse sc : studentCourses) {
                try {
                    StudentCourseDTO dto = new StudentCourseDTO();
                    // 设置StudentCourse中的属性
                    dto.setId(sc.getId());
                    dto.setCourseId(sc.getCourseId());
                    dto.setProgress(sc.getProgress());
                    dto.setStatus(sc.getStatus());
                    
                    // 获取课程详情
                    Course course = courseMapper.selectById(sc.getCourseId());
                    if (course != null) {
                        dto.setTitle(course.getTitle());
                        dto.setCategory(course.getCategory());
                        dto.setLevel(course.getLevel());
                        dto.setCoverUrl(course.getCoverUrl());
                        dto.setIntroMd(course.getIntroMd());
                        dto.setPrice(course.getPrice());
                        log.info("获取课程详情成功 - 课程ID: {}, 标题: {}", sc.getCourseId(), course.getTitle());
                    } else {
                        log.warn("获取课程详情失败 - 课程不存在, 课程ID: {}", sc.getCourseId());
                        // 设置一些默认值，避免前端显示错误
                        dto.setTitle("未知课程 (ID: " + sc.getCourseId() + ")");
                        dto.setCategory("未分类");
                        dto.setLevel("未知");
                        dto.setCoverUrl("");
                        dto.setIntroMd("该课程信息不存在");
                        dto.setPrice(BigDecimal.ZERO);
                    }
                    
                    // 设置最后学习时间
                    dto.setLastLearnTime(sc.getLastLearnTime() != null ? sc.getLastLearnTime() : sc.getPaidAt());
                    
                    // 设置下一学习点（这里简单模拟，实际项目可能需要根据学习进度计算）
                    String nextPoint;
                    if (sc.getProgress() < 0.33f) {
                        nextPoint = "第1章 基础入门";
                    } else if (sc.getProgress() < 0.66f) {
                        nextPoint = "第2章 进阶学习";
                    } else if (sc.getProgress() < 1.0f) {
                        nextPoint = "第3章 高级应用";
                    } else {
                        nextPoint = "课程已完成";
                    }
                    dto.setNextLearningPoint(nextPoint);
                    
                    result.add(dto);
                } catch (Exception e) {
                    log.error("处理单个课程信息异常 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, sc.getCourseId(), e.getMessage());
                    System.out.println("处理单个课程信息异常详细信息：");
                    e.printStackTrace();
                    // 继续处理下一个课程，不影响整体结果
                }
            }
            

            log.info("获取学生课程列表成功 - 学生ID: {}, 返回课程数: {}", studentId, result.size());
            return result;
        } catch (Exception e) {
            log.error("获取学生课程列表异常 - 学生ID: {}, 错误: {}", studentId, e.getMessage());
            System.out.println("获取学生课程列表异常详细信息：");
            e.printStackTrace();
            // 返回空列表，避免前端出错
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean updateCourseProgress(Integer studentId, Integer courseId, Float progress) {
        log.info("更新课程学习进度 - 学生ID: {}, 课程ID: {}, 进度: {}", studentId, courseId, progress);
        
        try {
            // 验证进度值
            if (progress < 0 || progress > 1) {
                log.warn("更新课程学习进度失败 - 进度值无效: {}", progress);
                return false;
            }
            
            // 首先检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("更新课程学习进度失败 - 课程不存在, 课程ID: {}", courseId);
                return false;
            }
            
            // 检查是否已订阅该课程
            QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("student_id", studentId)
                       .eq("course_id", courseId)
                       .eq("status", "paid");
            
            Long count = studentCourseMapper.selectCount(queryWrapper);
            if (count == null || count == 0) {
                log.warn("更新课程学习进度失败 - 未订阅课程, 学生ID: {}, 课程ID: {}", studentId, courseId);
                return false; // 未订阅该课程
            }
            
            // 更新进度
            UpdateWrapper<StudentCourse> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("student_id", studentId)
                        .eq("course_id", courseId)
                        .set("progress", progress)
                        .set("last_learn_time", LocalDateTime.now());
            
            int result = studentCourseMapper.update(null, updateWrapper);
            log.info("更新课程学习进度结果 - 学生ID: {}, 课程ID: {}, 结果: {}", studentId, courseId, result > 0);
            return result > 0;
        } catch (Exception e) {
            log.error("更新课程学习进度异常 - 学生ID: {}, 课程ID: {}, 错误: {}", studentId, courseId, e.getMessage());
            System.out.println("更新课程学习进度异常详细信息：");
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> getMonthlyActiveStudents() {
        List<Map<String, Object>> result = new ArrayList<>();
        // 直接用 MyBatis-Plus 无法 group by month，使用自定义 SQL
        List<Map<String, Object>> dbResult = studentCourseMapper.getMonthlyActiveStudents();
        if (dbResult != null) {
            result.addAll(dbResult);
        }
//        System.out.println(result);
        return result;
    }

    @Override
    public List<Map<String, Object>> getDailyActiveStudents() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> dbResult = videoStudentCourseProgressMapper.getDailyActiveStudents();
        if (dbResult != null) {
            result.addAll(dbResult);
        }
//        System.out.println(result);
        return result;
    }

    @Override
    public List<Map<String, Object>> getPendingAssignments(Long userId) {
        try {
            // 直接返回所有作業，不過濾課程
            List<Map<String, Object>> allAssignments = questionMapper.getQuestionsByCourseId(null);
            List<Map<String, Object>> pendingAssignments = new ArrayList<>();
            
            if (allAssignments == null || allAssignments.isEmpty()) {
                return pendingAssignments;
            }
            
            // 處理每個作業
            for (Map<String, Object> assignment : allAssignments) {
                if (assignment == null || !assignment.containsKey("id")) {
                    continue;
                }
                
                Long questionId = ((Number) assignment.get("id")).longValue();
                
                // 檢查學生是否已完成此作業
                Integer count = studentAnswerMapper.countByUserIdAndQuestionId(userId.intValue(), questionId.intValue());
                
                // 如果未完成（count=0），則添加到待辦列表
                if (count == 0) {
                    Map<String, Object> pendingAssignment = new HashMap<>();
                    pendingAssignment.put("questionId", questionId);
                    pendingAssignment.put("title", assignment.containsKey("title") ? assignment.get("title") : "未知作業");
                    pendingAssignment.put("courseId", 1); // 使用默認課程 ID
                    pendingAssignment.put("courseName", "未知課程");
                    pendingAssignment.put("courseImage", "");
                    
                    pendingAssignments.add(pendingAssignment);
                }
            }
            
            return pendingAssignments;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}

